/*            Copyright(c) 2006-2008 Dave Sexton           *
 * http://www.codeplex.com/DocProject                      *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing.Design;
using EnvDTE80;

namespace DaveSexton.DocProject.Sandcastle.BuildComponents.Editors
{
	internal sealed class SandcastleBuildComponentConfigFileEditor : UITypeEditor
	{
		#region Constructors
		/// <summary>
		/// Constructs a new instance of the <see cref="SandcastleBuildComponentConfigFileEditor" /> class.
		/// </summary>
		public SandcastleBuildComponentConfigFileEditor()
		{
		}
		#endregion

		#region Methods
		public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
		{
			return UITypeEditorEditStyle.Modal;
		}

		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			SandcastleBuildComponent component = (SandcastleBuildComponent) value;

			if (component == null)
				return base.EditValue(context, provider, value);
			else if (DocProjectEnvironment.RunningInVisualStudio)
				EditConfigurationFile(component);
			else
				System.Diagnostics.Process.Start(component.ConfigurationFile);

			return false;
		}

		private static void EditConfigurationFile(SandcastleBuildComponent component)
		{
			DTE2 dte = VSEnvironmentHost.DTE;

			EnvDTE.Window window = dte.OpenFile(EnvDTE.Constants.vsViewKindPrimary, component.ConfigurationFile);

			window.Activate();

			EnvDTE.TextSelection selection = window.Document.Selection as EnvDTE.TextSelection;

			if (selection != null)
			{
				try
				{
					selection.MoveToLineAndOffset(component.LineNumber, 1, false);
					selection.SelectLine();
				}
				// Thrown in testing when the configuration document changed on disc after being 
				// loaded into the options class if the line number is no longer valid.
				catch (ArgumentException) { }
			}
		}
		#endregion
	}
}
